<template>
  <div style="width:203px">
    <a-select :value="newValue"
              @change="handleChange">
      <a-select-option value="this">
        {{ widget.label || '数据提交人' }}
      </a-select-option>
      <a-select-option value="lucy"
                       @click="openSelectUnit">
        {{ strValue || '自定义' }}
      </a-select-option>
    </a-select>
    <component :is="widget.component"
               v-show="false"
               :value="unitUserValue"
               ref="ZSelectUnit"
               @change="selectUnitChange" />
  </div>
</template>

<script>
import { getTreeUnitUsersByUserIds, getTreeUnitListByUserIds } from './../api/select'
export default {
  name: 'Submitter',
  props: {
    value: {
      type: String | Array,
      default: ''
    },
    widget: {
      type: Object,
      default: () => { }
    },
    formData: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      unitUserValue: [],
      newValue: '',
      strValue: ''
    }
  },
  watch: {
    'formData.targetValue': {
      handler (value) {
        if (!value) return
        if (value == 'this') {
          this.newValue = 'this'
        } else if (value instanceof Array) {
          this.newValue = 'lucy'
          this.unitUserValue = value
        }
      },
      immediate: true,
      deep: true
    },
    unitUserValue: {
      handler (value) {
        if (this.widget.component == 'ZSelectUser') {
          getTreeUnitUsersByUserIds(value.join(',')).then(res => {
            this.strValue = res.map(item => {
              return item.name
            }).join(',')
          })
        } else {
          getTreeUnitListByUserIds(value.join(',')).then(res => {
            this.strValue = res.map(item => {
              return item.name
            }).join(',')
          })
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    handleChange (val) {
      if (val == 'lucy') {
        this.$emit('input', this.unitUserValue)
        this.$emit('change', this.unitUserValue)
        this.formData.targetValue = this.unitUserValue
      } else if (val == 'this') {
        this.$emit('input', val)
        this.$emit('change', val)
        this.formData.targetValue = val
      }
    },
    openSelectUnit () {
      this.$refs.ZSelectUnit.openDialog()
    },
    selectUnitChange (val) {
      this.$emit('input', this.unitUserValue)
      this.$emit('change', this.unitUserValue)
      this.newValue = 'lucy'
      this.formData.targetValue = this.unitUserValue
      this.unitUserValue = val
    }
  }
}
  </script>

<style>
</style>